package com.nielsenedu.WeatherData;

import java.util.ArrayList;
import java.util.Arrays;

public class WeatherData {

	/** Guaranteed not to be null and to contain only non-null entries */
	public ArrayList<Double> temperatures;

	public WeatherData(double[] temperatures) {
		this.temperatures = new ArrayList<>(temperatures.length);
		for(double temperature : temperatures)
			this.temperatures.add(temperature);
	}

	/**
	 * Cleans the data by removing from temperatures all values that are
	 * less than lower and all values that are greater than upper, as
	 * described in part (a)
	 */
	public void cleanData(double lower, double upper) {
		// If we loop forward, we may skip values because we
		// are removing elements.
		for(int i = temperatures.size()-1 ; i >= 0; i--) {
			double t = temperatures.get(i);
			if(t < lower || t > upper) {
				temperatures.remove(i);
			}
		}
	}
	
	public void cleanDataForward(double lower, double upper) {
		// Trick to avoid skipping over a value when we loop forward
		for(int i = 0; i < temperatures.size(); i++) {
			double t = temperatures.get(i);
			if(t < lower || t > upper) {
				temperatures.remove(i);
				i--; // i-- then i++ means no increment of index
			}
		}
	}

	/**
	 * Returns the length of the longest heat wave found in temperatures,
	 * as described in part (b)
	 * Precondition: There is at least one heat wave in temperatures
	 *               based on threshold.
	 */
	public int longestHeatWave(double threshold) {
		int longest = 0;
		int current = 0;
		for(double t : temperatures) {
			if(t > threshold) {
				current++;
			} else {
				current = 0;
			}
			if(current > longest) {
				longest = current;
			}
		}
		return longest;
	}

	public String toString() {
		return temperatures.toString();
	}
	
	private static double[] getDataSet(int series) {
		if(series == 1) {
			return new double[] {
				99.1, 142.0, 85.0, 85.1, 84.6, 94.3, 124.9, 98.1, 101.0, 102.5 };
		} else {
			return new double[] {
				100.5, 98.5, 102.0, 103.9, 87.5, 105.2, 90.3, 94.8, 109.1, 102.1, 107.4, 93.2
			};
		}
	}

	public static void main(String[] args) {
		WeatherData wd;
		// Test backwards loop cleanData
		wd = new WeatherData(getDataSet(1));
		System.out.println(wd);
		wd.cleanData(86.0, 120.0);
		System.out.println(wd);
		
		// Test forwards loop cleanDataForwards
		wd = new WeatherData(getDataSet(1));
		wd.cleanDataForward(86.0, 120.0);
		System.out.println(wd + "\n");

		// Test longestHeatWave
		wd = new WeatherData(getDataSet(2));
		System.out.println(wd);
		double threshold;
		threshold = 100.5;
		System.out.println(threshold + ": " + wd.longestHeatWave(threshold));
		threshold = 95.2;
		System.out.println(threshold + ": " + wd.longestHeatWave(threshold));

	}

}
